﻿using CommunicationLib.Enums;
using CommunicationLib.Model;
using PLCdev.ViewModel;
using PlcLib;
using PlcLib.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PLCdev
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private byte[] GetBytes(int value)
        {
            byte[] result = new byte[value];
            result[0] = (byte)((value >> 24) & 0xff);
            result[1] = (byte)((value >> 16) & 0xff);
            result[2] = (byte)((value >> 8) & 0xff);
            result[3] = (byte)((value >> 0) & 0xff);
            return result;
        }
        private MainViewModel mainViewModel;

        public MainWindow()
        {
            InitializeComponent();
            mainViewModel = new MainViewModel();
            DataContext = mainViewModel;

            var array = BitConverter.GetBytes(100);
            var array2 = GetBytes(1000);
        }



        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                try
                {
                    Net net = new Net()
                    {
                        LocalIp = "127.0.0.1",
                        LocalPort = 502,
                        Ip = "192.168.56.1", 
                        Port = 502,
                        MaxMilliseconds = 5000
                    };

                    mainViewModel.OrmonPlc.Initialize(net);
                    var startResult = mainViewModel.OrmonPlc.Start();
                    
                    Dispatcher.Invoke(() =>
                    {
                        if (startResult.Sucess)
                        {
                            MessageBox.Show("连接成功！现在连接应该保持稳定。");
                        }
                        else
                        {
                            MessageBox.Show($"连接失败：{startResult.Message}");
                        }
                    });
                    
                    // 测试：等待10秒，看连接是否保持稳定
                    for (int i = 0; i < 10; i++)
                    {
                        Thread.Sleep(1000);
                        Dispatcher.Invoke(() =>
                        {
                            // 通过UI更新显示当前状态
                        });
                    }
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show($"连接异常：{ex.Message}");
                    });
                }
            });
        }

        // 添加新的按钮事件处理
        private void Button_Click_SetParam(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                SetPraram();
            });
        }

        private void SetPraram()
        {
            try
            {
                Command command = new Command(20, 1, DataType.WordHEX, OperactorMode.Write, AreaType.DM);
                var result = mainViewModel.OrmonPlc.Write(command, 789456);
                
                Dispatcher.Invoke(() =>
                {
                    if (result.Sucess)
                    {
                        MessageBox.Show("参数设置成功");
                    }
                    else
                    {
                        MessageBox.Show($"参数设置失败：{result.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() =>
                {
                    MessageBox.Show($"参数设置异常：{ex.Message}");
                });
            }
        }

      

        private void Button_Click_Read(object sender, RoutedEventArgs e)
        {
            // 使用异步方式避免UI卡死
            Task.Run(() =>
            {
                try
                {
                    Command command = new Command(2, 100, DataType.WordHEX, OperactorMode.Read, AreaType.DM);
                    var result = mainViewModel.OrmonPlc.Read(command);

                    // 回到UI线程显示结果
                    Dispatcher.Invoke(() =>
                    {
                        if (result.Sucess)
                        {
                            MessageBox.Show($"读取成功，数据：{result.Content}");
                        }
                        else
                        {
                            MessageBox.Show($"读取失败，错误信息：{result.Message}");
                        }
                    });
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show($"读取异常：{ex.Message}");
                    });
                }
            });
        }

        private async void Button_Click_ReadAsync(object sender, RoutedEventArgs e)
        {
            try
            {
                Command command = new Command(2, 100, DataType.WordHEX, OperactorMode.Read, AreaType.DM);
                var result = await mainViewModel.OrmonPlc.ReadAsync(command);

                if (result.Sucess)
                {
                    MessageBox.Show($"异步读取成功，数据：{result.Content}");
                }
                else
                {
                    MessageBox.Show($"异步读取失败，错误信息：{result.Message}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"异步读取异常：{ex.Message}");
            }
        }

        private void Button_Click_Write(object sender, RoutedEventArgs e)
        {
            Command command = new Command(100, 1, DataType.WordHEX, OperactorMode.Write, AreaType.DM);

            var result = mainViewModel.OrmonPlc.Write(command, 256);
            if (result.Sucess)
            {
                MessageBox.Show($"同步写入成功");
            }
        }

        private async void Button_Click_WriteAsync(object sender, RoutedEventArgs e)
        {
            try
            {
                Command command = new Command(100, 1, DataType.WordHEX, OperactorMode.Write, AreaType.DM);

                // 使用 await 而不是 .Result
                var result = await mainViewModel.OrmonPlc.WriteAsync(command, 256);

                if (result.Sucess)
                {
                    MessageBox.Show($"异步写入成功");
                }
                else
                {
                    MessageBox.Show($"异步写入失败，错误信息：{result.Message}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"异步写入异常：{ex.Message}");
            }
        }

        private void Button_Click_SendSyn(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                byte[] array = new byte[] { 0x46, 0x49, 0x4E, 0x53 };
                var result = mainViewModel.OrmonPlc.Send(array);
                if (result.Sucess)
                {
                    MessageBox.Show($"发送byte成功，数据：{result.Content}");
                }
                else
                {
                    MessageBox.Show($"发送byte失败，错误信息：{result.Message}");
                }
            });
        }

        private async void Button_Click_SendAsync(object sender, RoutedEventArgs e)
        {
            try
            {
                byte[] array = new byte[] { 0x46, 0x49, 0x4E, 0x53 };
                var result = await mainViewModel.OrmonPlc.SendAsync(array);
                if (result.Sucess)
                {
                    MessageBox.Show($"异步发送byte成功，数据：{array}");
                }
                else
                {
                    MessageBox.Show($"异步发送byte失败，错误信息：{result.Message}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"异步发送byte异常：{ex.Message}");
            }
        }

        /// <summary>
        ///  添加泛型读取按钮事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_ReadPLC(object sender, RoutedEventArgs e)
        {
            // 使用异步方式避免UI卡死
            Task.Run(() =>
            {

                Command command = new Command(2, 100, DataType.WordHEX, OperactorMode.Read, AreaType.DM);
                var result = mainViewModel.OrmonPlc.Read<int>(command);

                // 回到UI线程显示结果
                Dispatcher.Invoke(() =>
                {
                    if (result.Sucess)
                    {
                        MessageBox.Show($"读取成功，数据：{result.Content}");
                    }
                });
                //回复4个字长 - 》读两个int 或uint
                // 46 49 4E 53 00 00 00 1E 00 00 00 02 00 00 00 00 C0 00 02 00 34 00 00 01 00 FF 01 01 00 00  00 14 00 1E 01 02 03 04

                //回复2个字长 - 》读1个int 或uint 或float
                // 46 49 4E 53 00 00 00 1A 00 00 00 02 00 00 00 00 C0 00 02 00 34 00 00 01 00 FF 01 01 00 00  00 14 00 1E
                //var result2 = await mainViewModel.OrmonPlc.ReadAsync<string>(command);

                //// 回到UI线程显示结果
                //Dispatcher.Invoke(() =>
                //{
                //    if (result2.Sucess)
                //    {
                //        MessageBox.Show($"异步读取成功，数据：{result2.Content}");
                //    }
                //});
            });
        }
    }
}
